package com.humngyang.com.hmy.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.humngyang.com.hmy.entity.Role;
import com.humngyang.com.hmy.entity.User;
import com.humngyang.com.hmy.mapper.RoleAuthorityMapper;
import com.humngyang.com.hmy.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    RoleAuthorityMapper roleAuthorityMapper;

    /**
     * Author : hmy
     *
     * @date 2020/2/24 20:55
     * describution : 查询所有的角色
     **/
    public List<Role> getAllRole() {
        List<Role> roles = roleMapper.selectList(null);
        if (CollectionUtils.isEmpty(roles)) {
            return Collections.EMPTY_LIST;
        } else {
            return roles;
        }

    }

    public List<Map<String, Object>> getAllRoleMap() {
        List<Map<String, Object>> maps = roleMapper.selectMaps(null);
        if (CollectionUtils.isEmpty(maps)) {
            return Collections.EMPTY_LIST;
        } else {
            return maps;
        }
    }


    /**
     * Author : hmy
     *
     * @date 2020/2/28 7:10
     * describution :添加角色
     **/
    public Map<String, Object> addrole(Role role) {
        Map<String, Object> re = new HashMap<>();
        Role rolename = roleMapper.selectOne(new QueryWrapper<Role>().eq("rolename", role.getRolename()));
        if (StringUtils.isEmpty(role.getRoleid()) && rolename != null) {
            re.put("message", "该角色已经添加");
            re.put("flag", 0);
            return re;
        }
        if (StringUtils.isEmpty(role.getRoleid())) {
            role.setRoleid(UUID.randomUUID().toString().replace("-", ""));
            roleMapper.insert(role);
            re.put("flag", 1);
            return re;
        }

        roleMapper.updateById(role);
        re.put("flag", 1);
        return re;

    }

    /**
     * Author : hmy
     *
     * @date 2020/2/28 9:16
     * describution :根据id查找角色信息
     **/


    public Map<String, Object> getRoleById(String id) {
        Map<String, Object> map = new HashMap<>();
        Role role = roleMapper.selectById(id);
        map.put("flag", 1);
        if (role != null) {
            map.put("role", role);
        } else {
            map.put("role", Collections.EMPTY_MAP);
        }
        return map;
    }


    /**
     * Author : hmy
     *
     * @date 2020/2/28 13:09
     * describution :根据id删除角色信息，同时删除权限信息
     **/

    public void deleteByRoleid(String roleid) {
        roleMapper.deleteById(roleid);
        Map<String, Object> prames = new HashMap<>();
        prames.put("roleid", roleid);
        roleAuthorityMapper.deleteByMap(prames);
    }



}
